package com.example.myapplication01.service;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.Button;


public class ActivityMessenger extends Activity {
    /**
     * 与服务端交互的Messenger
     */
    Messenger mService = null;

    /** Flag indicating whether we have called bind on the service. */
    boolean mBound;

    /**
     * 实现与服务端链接的对象
     */
    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            /**
             * 通过服务端传递的IBinder对象,创建相应的Messenger
             * 通过该Messenger对象与服务端进行交互
             */
            mService = new Messenger(service);
            mBound = true;
        }

        public void onServiceDisconnected(ComponentName className) {
            // This is called when the connection with the service has been
            // unexpectedly disconnected -- that is, its process crashed.
            mService = null;
            mBound = false;
        }
    };

    public void sayHello(View v) {
        if (!mBound) return;
        // 创建与服务交互的消息实体Message
        Message msg = Message.obtain(null, MessengerService.MSG_SAY_HELLO, 0, 0);
        try {
            //发送消息
            mService.send(msg);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // setContentView(R.layout.activity_messenager);
        Button bindService= new Button(this);
        Button unbindService= new Button(this);
        Button sendMsg= new Button(this);

        bindService.setOnClickListener(v -> {
            Log.d("zj","onClick-->bindService");
            //当前Activity绑定服务端
            bindService(new Intent(ActivityMessenger.this, MessengerService.class), mConnection,
                    Context.BIND_AUTO_CREATE);
        });

        //发送消息给服务端
        sendMsg.setOnClickListener(v -> sayHello(v));


        unbindService.setOnClickListener(v -> {
            // Unbind from the service
            if (mBound) {
                Log.d("zj","onClick-->unbindService");
                unbindService(mConnection);
                mBound = false;
            }
        });
    }

}
